import router from '@/router';
import { useUserStoreHook } from '@/store/modules/user';
import { usePermissionStoreHook } from '@/store/modules/permission';
import { RouteRecordRaw } from 'vue-router';


import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { el } from 'element-plus/es/locale';
NProgress.configure({ showSpinner: false }); // 进度条

const permissionStore = usePermissionStoreHook();

// 白名单路由
const whiteList = ['/login', '/editPass', '/screenHome', '/screenOperate'];

router.beforeEach(async (to, from, next) => {
  NProgress.start();
  const hasToken = localStorage.getItem('accessToken');
  if (hasToken) {
    if (to.path === '/login') {
      // 如果已登录，跳转首页
      next({ path: '/' });
      NProgress.done();
    } else {
      // console.log('to', to)
      // console.log('from', from)
      // console.log("路由测试测试==》》", to.matched)
      const userStore = useUserStoreHook();  // 响应式本地，但是手动清除token无法响应
      if (userStore.userInfo.nickName) {
        if (to.matched.length === 0) {  // matched一个数组，包含当前路由的所有嵌套路径片段的路由记录 。路由记录就是 routes 配置数组中的对象副本 (还有在 children 数组)。
          next('/404') // 判断此跳转路由的来源路由是否存在，存在的情况跳转到来源路由，否则跳转到404页面
        } else {
          next()
        }
      } else {
        try {
          await userStore.getInfo()
          const menuTreeVue = userStore.menuTreeVue;
          const accessRoutes = permissionStore.generateRoutes(menuTreeVue)
          permissionStore.setRoutes(accessRoutes)
          if (accessRoutes.length < 1) {
            userStore.menuTreeVue = []
            next()
          }

          // console.log()
          accessRoutes.forEach((route: any) => {
            router.addRoute(route);
          });
          // router.addRoute( {path: '*', component: () => import('@/views/error-page/404.vue'),
          // meta: { hidden: true }});


          // next()
          next({ ...to, replace: true });
        } catch (error) {

          console.log("发生错误==", error)
          // 移除 token 并跳转登录页
          await userStore.resetToken();
          next(`/login?redirect=${to.path}`);
          NProgress.done();
        }
      }
    }
  } else {
    // 未登录可以访问白名单页面
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      next(`/login?redirect=${to.path}`);
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  NProgress.done();
});
